/*
 * @Author: 李金深 2896583081@qq.com
 * @Date: 2023-06-26 17:21:35
 * @LastEditors: 李金深 2896583081@qq.com
 * @LastEditTime: 2023-06-27 09:02:40
 * @FilePath: /com.huizhouyiren.web.d0101/src/hooks/audioContext.js
 * @Description: 音频播放 (该功能暂时不能正常使用，同一首歌曲暂停后无法再次播放：处理方案暂未找到)
 */
import mitt from '@/mitt/index'
let ctx = new (window.AudioContext || window.webkitAudioContext())()
let source = null // 创建音频源头节点
/**
 * @description: 播放
 * @return {*}
 */
async function playAudio(url) {
  // if (originalSrc != url) {
  //   const audioBuffer = await loadAudio(url)
  //   playSound(audioBuffer)
  //   return
  // }
  if (ctx.state === 'running') {
    ctx.suspend()
  } else {
    console.log('嫁给')
    source = ctx.createBufferSource()
    const audioBuffer = await loadAudio(url)
    playSound(audioBuffer)
  }
}
/**
 * @description: 暂停
 * @return {*}
 */
async function pauseAudio() {
  console.log(ctx.state)
  if (ctx.state === 'running') {
    ctx.suspend()
  } else if (ctx.state === 'suspended') {
    ctx.resume(0)
  }
}
/**
 * @description: 停止
 * @return {*}
 */
async function stopAudio() {
  source.stop(0)
}
async function loadAudio(url) {
  try {
    const res = await fetch(
      'https://ws.stream.qqmusic.qq.com/C400002ExFMX2Jt6gv.m4a?guid=405983862&vkey=25608D435CFE950149EDB9B588B48A0981414343C5EE7AF32927C3B7BB8C1ED3C97CDC5D50F9AF7C92A19C44641D50E4752C8C5EF2163AF2&uin=626567678&fromtag=103032'
    )
    const arrayBuffer = await res.arrayBuffer() // byte array字节数组
    const audioBuffer = await ctx.decodeAudioData(arrayBuffer, function (decodeData) {
      return decodeData
    })
    return audioBuffer
  } catch (err) {
    mitt.emit('messageTip', {
      type: 'error',
      msg: 'msg.playError',
      useTranslate: true
    })
  }
}
async function playSound(audioBuffer) {
  console.log('bofang')
  source.buffer = audioBuffer // 设置数据
  source.loop = false //设置，循环播放
  source.connect(ctx.destination) // 头尾相连
  // 可以对音频做任何控制
  source.start(0) //立即播放
}
export default function () {
  mitt.on('audioPlay', (url) => {
    playAudio(url)
  })
  mitt.on('audioPause', () => {
    pauseAudio()
  })
  mitt.on('audioStop', () => {
    stopAudio()
  })
}
